/*
 * Copyright (C) 2010 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.zxing.camera;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;

import com.ciwong.libs.utils.CWLog;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public final class PreviewCallback implements Camera.PreviewCallback {

    private static final String TAG = PreviewCallback.class.getSimpleName();

    private final CameraConfigurationManager configManager;

    private final boolean useOneShotPreviewCallback;

    private Handler previewHandler;

    private int previewMessage;

    private byte[] currentData;

    /**
     * 需不需要用zxing扫描
     */
    private boolean needUseZxingScan = true;

    PreviewCallback(CameraConfigurationManager configManager,
                    boolean useOneShotPreviewCallback) {
        this.configManager = configManager;
        this.useOneShotPreviewCallback = useOneShotPreviewCallback;
    }

    public void setHandler(Handler previewHandler, int previewMessage) {
        this.previewHandler = previewHandler;
        this.previewMessage = previewMessage;
    }

    public byte[] getCurrentData() {
        return currentData;
    }

    public void onPreviewFrame(byte[] data, final Camera camera) {

        Log.d(TAG, "------>>> Got preview callback ");

        currentData = data;
        Point cameraResolution = configManager.getCameraResolution();
        if (!useOneShotPreviewCallback) {
            camera.setPreviewCallback(null);
        }
        if (previewHandler != null) {
            Message message = previewHandler.obtainMessage(previewMessage,
                    cameraResolution.x, cameraResolution.y, data);

             CWLog.e(TAG, "onPreviewFrame w = " + cameraResolution.x + " h =" + cameraResolution.y+" data.size:"+data.length);
            message.sendToTarget();
            previewHandler = null;
          /*  new Thread(new Runnable() {
                @Override
                public void run() {
                    saveBitmap(camera,currentData);
                }
            }).start();*/
        } else {
            Log.d(TAG, "Got preview callback, but no handler for it");
        }
        // ///////////////////
    }

    public void setNeedUseZxingScan(boolean needUseZxingScan) {
        this.needUseZxingScan = needUseZxingScan;
    }

    public boolean isNeedUseZxingScan() {
        return needUseZxingScan;
    }

    private void saveBitmap(Camera camera, byte[] currentData){


        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File( Environment.getExternalStorageDirectory()+"/aatest/"+ fileName);

        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }


        //处理data
        Camera.Size previewSize = camera.getParameters().getPreviewSize();//获取尺寸,格式转换的时候要用到
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;
        YuvImage yuvimage = new YuvImage(
                currentData,
                ImageFormat.NV21,
                previewSize.width,
                previewSize.height,
                null);
        ByteArrayOutputStream   baos= new ByteArrayOutputStream();
        yuvimage.compressToJpeg(new Rect(0, 0, previewSize.width, previewSize.height), 100, baos);// 80--JPG图片的质量[0-100],100最高
        byte[] rawImage= baos.toByteArray();
        //将rawImage转换成bitmap
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        Bitmap bitmap = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length, options);


        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fileOutputStream);
            fileOutputStream.close();
        } catch (IOException e) {

        }
    }

}
